package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.AddressBook;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.SMSUtils;
import com.itheima.reggie.utils.ValidateCodeUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @Author: fengfeng
 * @Date: 2023/07/18/16:32
 * @Description: 业余爱好者
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user) {
        // 获取手机号
        String phone = user.getPhone();
        if (StringUtils.isEmpty(phone)) {
            return R.success("请输入手机号");
        }
        // 生成随机的4位验证码
        String code = ValidateCodeUtils.generateValidateCode(4).toString();
        // 调用阿里云提供的服务api完成发送短信
//        SMSUtils.sendMessage();
        // 需要将生成的验证码保存到session
        return null;
    }

    /**
     * 移动端用户登录
     *
     * @return
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession session) {
        // 获取手机号
        String phone = map.get("phone").toString();
        // 判断当前手机号对应的用户是否为新用户，如果是新用户就自动完成注册
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getPhone, phone);
        User user = userService.getOne(lambdaQueryWrapper);
        if (user != null) {
            session.setAttribute("user", user.getId());
            return R.success(user);
        }
        user = new User();
        user.setPhone(phone);
        user.setStatus(1);
        userService.save(user);
        session.setAttribute("user", user.getId());
        return R.success(user);
    }


}
